/**
 * Project Name:leaf-manager-web
 * File Name:ExportCsvUtil.java
 * Package Name:com.hzkans.leaf.user.web.utils
 * Date:2017年4月24日下午5:01:05
 *
 */

package com.cgm.controller.utils;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.cgm.common.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * ClassName:ExportCsvUtil Function: TODO ADD FUNCTION. Reason: TODO ADD REASON.
 * Date: 2017年4月24日 下午5:01:05
 * 
 * @author ly
 * @see
 */
public class ExportCsvUtil {

	public static final Logger log = LoggerFactory
			.getLogger(ExportCsvUtil.class);

	public static void exportCsv(HttpServletResponse response, String title,
			List<String> headers, List<List<String>> rows)
			throws Exception {

		try {
			String headerStr = null;

			// response.reset();

			// response.setContentType("application/csv;charset=utf-8");
			// response.setContentType("application/csv;charset=GBK");
			// response.setContentType("application/csv;charset=UTF-8");

			response.setHeader(
					"Content-Disposition",
					"attachment;filename="
							+ title
							+ DateUtil.format(new Date(),
									DateUtil.NORMAL_DATETIME_PATTERN) + ".csv");

			// 中文乱码
			// response.setCharacterEncoding("gb2312");
			// response.setCharacterEncoding("GBK");
			// response.setCharacterEncoding("UTF-8");

			String content = "";

			headerStr = generateHeader(headers);
			content += headerStr + "\r\n";
			content += generateContent(rows);

			OutputStream os = response.getOutputStream();

			// OutputStreamWriter os = new OutputStreamWriter(
			// response.getOutputStream(), "UTF-8");

			// os.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,
			// (byte) 0xBF }));

			os.write(content.getBytes("GBK"));

			// os.flush();

			os.close();

			// PrintWriter out = response.getWriter();

			// headerStr = generateHeader(headers);

			// out.println(headerStr);

			// generateRows(rows, out);

			// out.flush();
			// out.close();

		} catch (Exception e) {
			log.error(" exportCsv error :{} ",
					ExceptionUtils.getFullStackTrace(e));

			throw new Exception(e);
		}
	}

	private static String generateHeader(List<String> headers)
			throws Exception {
		String headerStr = "";
		if (CollectionUtils.isEmpty(headers)) {
			log.error(" generateHeader error : headers is null ");
			throw new Exception(
					" generateHeader error : headers is null ");
		}
		for (String header : headers) {
			headerStr += header + ",";
		}
		headerStr = headerStr.substring(0, headerStr.length() - 1);
		// log.info(" headerStr:{}", headerStr);
		return headerStr;
	}

	private static void generateRows(List<List<String>> rows, PrintWriter out)
			throws Exception {
		if (CollectionUtils.isEmpty(rows)) {
			log.error(" generateRows error : rows is empty ");
			throw new Exception(" generateRows error : rows is empty ");
		}
		for (List<String> row : rows) {
			if (CollectionUtils.isEmpty(row)) {
				log.error(" generateRows error : row is empty ");
				throw new Exception(
						" generateRows error : row is empty ");
			}
			String rowStr = "";
			for (String grid : row) {
				if (StringUtils.isNotEmpty(grid)) {
					grid = grid.replace(",", "，");
					rowStr += grid + ",";
				} else {
					rowStr += " ,";
				}
			}
			rowStr = rowStr.substring(0, rowStr.length() - 1);
			// log.info(" rowStr:{} ", JsonUtil.toJson(rowStr));
			out.println(rowStr);
		}
	}

	private static String generateContent(List<List<String>> rows)
			throws Exception {
		if (CollectionUtils.isEmpty(rows)) {
			log.error(" generateRows error : rows is empty ");
			throw new Exception(" generateRows error : rows is empty ");
		}
		String content = "";
		for (List<String> row : rows) {
			if (CollectionUtils.isEmpty(row)) {
				log.error(" generateRows error : row is empty ");
				throw new Exception(
						" generateRows error : row is empty ");
			}
			String rowStr = "";
			for (String grid : row) {
				if (StringUtils.isNotEmpty(grid)) {
					grid = grid.replace(",", "，");
					rowStr += grid + ",";
				} else {
					rowStr += " ,";
				}
			}
			rowStr = rowStr.substring(0, rowStr.length() - 1);
			// log.info(" rowStr:{} ", JsonUtil.toJson(rowStr));
			content += rowStr + "\r\n";
		}

		return content;
	}

	public static void main(String[] args) {
		String headerStr = "1,2,";
		// headerStr = headerStr.substring(0, headerStr.length() - 1);
		headerStr = headerStr.replace(",", "，");
		System.out.println(headerStr);
		// System.out.println(str);
	}

}
